<?php
session_start(); // 开始会话

// 检查是否有登出请求
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
    session_unset(); // 清除会话变量
    session_destroy(); // 销毁会话
    header("Location: login.html"); // 重定向到登录页面
    exit();
}
?>

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>欢迎来到陌上的网站</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>欢迎来到陌上的留言板</h1>

        <?php
        // 调试信息
        if (isset($_SESSION['username'])) {
            echo "<p>欢迎, " . htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8') . "! <a href='?action=logout'>登出</a></p>";
        } else {
            echo "<p>请 <a href='login.html'>登录</a> 以发布留言。</p>";
        }
        ?>

        <?php if (isset($_SESSION['username'])): ?>
        <form action="post_message.php" method="post">
            <textarea name="message" rows="4" cols="50" placeholder="请输入您的留言" required></textarea><br>
            <input type="submit" value="提交留言">
        </form>
        <?php endif; ?>

        <h2>留言列表</h2>
        <?php
        $servername = "localhost";
        $db_username = "陌上";
        $db_password = "123456";
        $dbname = "陌上";

        $conn = new mysqli($servername, $db_username, $db_password, $dbname);

        if ($conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }

        $sql = "SELECT id, message, created_at FROM messages ORDER BY created_at DESC";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo "<div class='message'>";
                echo "<p>" . htmlspecialchars($row['message'], ENT_QUOTES, 'UTF-8') . "</p>";
                echo "<p><small>时间: " . htmlspecialchars($row['created_at'], ENT_QUOTES, 'UTF-8') . "</small></p>";
                if (isset($_SESSION['username'])) {
                    echo "<form action='delete_message.php' method='post'>";
                    echo "<input type='hidden' name='id' value='" . htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8') . "'>";
                    echo "<input type='submit' value='删除'>";
                    echo "</form>";
                }
                echo "</div>";
            }
        } else {
            echo "暂无留言";
        }

        $conn->close();
        ?>
    </div>
</body>
</html>
